using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.Plan;
using B.S.XZYData.Api.Read.Dto.Plan;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Plan
{
    /// <summary>
    /// 获取生产计划详情处理器
    /// </summary>
    public class GetPlanDetailHandler : IRequestHandler<GetPlanDetailCommand, ApiResult<PlanDetailDto>>
    {
        private readonly IBaseRepository<PlanModel> _planRepo;
        private readonly IBaseRepository<ProductModel> _productRepo;
        private readonly IMapper _mapper;

        public GetPlanDetailHandler(
            IBaseRepository<PlanModel> planRepo,
            IBaseRepository<ProductModel> productRepo,
            IMapper mapper)
        {
            _planRepo = planRepo;
            _productRepo = productRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<PlanDetailDto>> Handle(GetPlanDetailCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<PlanDetailDto>();

            try
            {
                // 获取计划基本信息
                var plan = _planRepo.GetAll()
                    .Where(x => x.Id == request.PlanId)
                    .ToList()
                    .FirstOrDefault();

                if (plan == null)
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "未找到指定的生产计划";
                    return res;
                }

                // 获取关联到该计划的产品列表
                var products = _productRepo.GetAll()
                    .Where(x => x.PlanId == request.PlanId)
                    .OrderBy(x => x.Id)
                    .ToList();

                // 映射到DTO
                var planDetailDto = _mapper.Map<PlanDetailDto>(plan);
                planDetailDto.Items = _mapper.Map<List<PlanProductDto>>(products);

                res.Data = planDetailDto;
                res.Code = ApiEnum.Success;
                res.Msg = "获取生产计划详情成功";
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"获取生产计划详情失败：{ex.Message}";
            }

            return res;
        }
    }
} 